<template>
    <div>
        <!--面包屑导航区域-->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>权限管理</el-breadcrumb-item>
            <el-breadcrumb-item>角色列表</el-breadcrumb-item>
        </el-breadcrumb>

        <el-card >
            <!--添加角色-->
            <el-button type="primary">添加角色</el-button>

            <!--角色列表区域-->
            <el-table :data="rolesList" border stripe style="width: 100%">
                <el-table-column type="expand">
                    <template slot-scope="scope">
                      <el-row :class="['bdbottom',i1 === 0 ? 'bdtop':'','vcenter']" v-for="(item1,i1) in scope.row.children" :key="item1.id">
                          <!--渲染一级权限  共占5列-->
                          <el-col :span="5">
                              <el-tag closable @close="deltagClicked(scope.row,item1.id)">{{item1.authName}}</el-tag>
                              <i class="el-icon-caret-right"></i>
                          </el-col>
                          <!--渲染二，三级权限 -->
                          <el-col :span="19">
                             <el-row :class="[i2 === 0 ? '':'bdtop','vcenter']" v-for="(item2,i2) in item1.children" :key="item2.id">
                                 <el-col :span="6">
                                     <el-tag type="success" closable @close="deltagClicked(scope.row,item2.id)">{{item2.authName}}</el-tag>
                                     <i class="el-icon-caret-right"></i>
                                 </el-col>
                                 <el-col :span="13">
                                     <el-tag type="warning" v-for="(item3,i3) in item2.children" :key="item3.id" closable @close="deltagClicked(scope.row,item3.id)">{{item3.authName}}</el-tag>
                                 </el-col>
                             </el-row>
                          </el-col>
                      </el-row>
                    </template>
                </el-table-column>
                <!--添加索引列-->
                <el-table-column type="index" label="#"></el-table-column>
                <el-table-column prop="roleName" label="角色名称"></el-table-column>
                <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
                <el-table-column label="操作" width="300px" >
                    <template slot-scope="scope">
                        <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row)">编辑</el-button>
                        <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeUserById(scope.row)">删除</el-button>
                        <el-button type="warning" icon="el-icon-setting" size="mini" @click="showSetRightDialog(scope.row)">分配角色</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-card >

        <!--分配权限-->
        <el-dialog title="分配角色" :visible.sync="addDialogVisible" width="50%" @close="setRightDialogClosed">
            <!--内容主题区域-->
            <!--show-checkbox显示前面的选择框
                node-key="id" 根据id关联是否选中对于tree的选择框
                default-expand-all = true tree节点全部展开
                ref 给树形结构添加引用，为了拿到需要的值
            -->
            <el-tree :data="rightList" :props="treeProps" :default-checked-keys="defKeys" ref="treeRef" show-checkbox node-key="id" default-expand-all ></el-tree>

            <!--底部区域-->
            <span slot="footer" class="dialog-footer">
                <el-button @click="addDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="allotRights">确 定</el-button>
            </span>
        </el-dialog>

    </div>
</template>

<script>
    export default {
       data(){
           return {
               rolesList:[],
               addDialogVisible:false,
               //所有权限列表数据
               rightList:[],
               //树形控件的属性绑定对象
               treeProps:{
                   children: 'children',
                   label: 'authName'
               },
               //默认选中的id值
               defKeys:[],
               //角色id
               roleId:''
           }
       },
       created() {
            this.getRolesList()
       },
       methods:{
           async getRolesList(){
               const {data:res} = await this.$http.get('roles')
               if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
               this.rolesList = res.data
               console.log(res)
           },
           async deltagClicked (role, rolesid){
               console.log(role)
               const confirmResult = await this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
                   confirmButtonText: '确定',
                   cancelButtonText: '取消',
                   type: 'warning'
               }).catch(err => err);
               //用户点击确定会返回confirm 字符串
               //   用户点击取消会返回cancel catch捕获错误信息
               // console.log(confirmResult);
               if (confirmResult !== 'confirm') {
                   return this.$message.info('已取消删除')
               }
               const {data:res} = await this.$http.delete(`roles/${role.id}/rights/${rolesid}`)
               if (res.meta.status !== 200) {
                   return this.$message.error(res.meta.msg)
               }
               this.$message.success(res.meta.msg)
               //不要调用刷新数据接口 直接把返回值赋值就不需要重新渲染列表页
               role.children = res.data
           },
           //展示分配权限的对话框
           async showSetRightDialog(role){
               this.roleId = role.id
               const {data:res} = await this.$http.get('rights/tree')
               if (res.meta.status !== 200) {
                   return this.$message.error(res.meta.msg)
               }
               this.$message.success(res.meta.msg)
               this.rightList = res.data
               //递归获取三级节点的id 数组
               this.getLeafKeys(role,this.defKeys)
               this.addDialogVisible = true
           },
           //通过递归的形式，获取角色下的所有哦三级权限的id,并保存到defkeys数组中
           getLeafKeys(node, arr) {
               //判断是否为三级节点,三级节点不包含children属性
               if (!node.children) {
                   // arr 添加id
                   return arr.push(node.id);
               }
               node.children.forEach(item =>
                    this.getLeafKeys(item,arr))
           },
           // 监听对话框关闭，清除defKeys中的数据
           setRightDialogClosed(){
               this.defKeys = [];
           },
           //点击为角色分配权限，确定上传数据
           async allotRights(){
               const keys = [
                   ...this.$refs.treeRef.getCheckedKeys(),
                   ...this.$refs.treeRef.getHalfCheckedKeys()
               ]
               const idStr = keys.join(',')
               const { data: res } = await this.$http.post(
                   `roles/${this.roleId}/rights`,
                   { rids: idStr }
               )
               if (res.meta.status !== 200) {
                   return this.$message.error('分配权限失败！')
               }
               this.$message.success('分配权限成功！')
               this.getRolesList()
               this.addDialogVisible = false
           }
       }
    }
</script>

<style scoped>
    .el-tag {
        margin: 7px;
    }

    /*设置上，下分割线*/
    .bdtop {
        border-top: 1px solid #eee;
    }

    .bdbottom {
        border-bottom: 1px solid #eee;
    }

    /*设置子样式权限标签居中对齐*/
    .vcenter {
        display: flex;
        align-items: center;
    }
</style>